import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */

  data: {
    address:{},
    cart:[],
    totalPrice:"",
    totalNum:""
  },

  onShow(){
    // 将存进缓存的数据储存进地址
  const address =wx.getStorageSync("address");
   let cart = wx.getStorageSync("cart")||[];
   //判断有勾选的商品
   cart = cart.filter(v=>v.check);
   this.setData({address})
  // 遍历购物车数组
  let totalPrice =0;
  let totalNum = 0;
  //遍历循环购物车数组 计算总价格和全选按钮
  cart.forEach(v => {
    if(v.check){
      totalPrice+=v.num*v.goods_price,
      totalNum += v.num;
    }
  });
  //当购物车数组为空 不勾选全选框
  this.setData({
    cart,
    totalPrice,
    totalNum
  })
  },
    async handleOrderPay(){
    try {
        //获取缓存中的token、
       const token =  wx.getStorageSync("token");
        
        if(!token){
        // 如果没有返回支付页面然后获取用户的各种参数请求token
        wx.navigateTo({
          url: '/pages/auth/auth',  
        });
        return;
              
        }
         // 3 创建订单
      // 3.1 准备 请求头参数
       const header = { Authorization: token };
      // 3.2 准备 请求体参数
      const order_price = this.data.totalPrice;
      const consignee_addr = this.data.address.provinceName+this.data.address.cityName+this.data.address.countyName+this.data.address.detailInfo
      const cart = this.data.cart;
      let goods = [];
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods };
      // 4 准备发送请求 创建订单 获取订单编号
      const res = await request({ url: "/my/orders/create", method: "POST", data: orderParams,header })
      const {order_number} = res.data.message
      //发起预支付接口
      const result = await request({url:"/my/orders/req_unifiedorder",method:"post",header,data:{order_number}})
      const {pay} = result.data.message
        //发起支付(因为是自己的appid 生成的token是别人的不对应 所以支付失败)
       await requestPayment(pay);
       //查询后台订单状态
       await request({url:"/my/orders/chkOrder",method:"post",header,data:{order_number}});
      await showToast({title:"支付成功"})
       
  
    } catch (err) {
      //自动将购物车选择的商品移除
      let newCart = wx.getStorageSync("cart");
      newCart =  newCart.filter(v=>!v.check);
     wx.setStorageSync('cart', newCart);
     //提示后跳转到订单界面
      await showToast({title:"因为无企业微信无法支付，所以默认支付成功"})
      wx.navigateTo({
        url: '/pages/order/order',
      });
        
        
    }
  }
})